package com.ice.work.moment.crawler.strategy;

import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.honeybee.cloud.framework.base.context.SpringContextHolder;
import com.honeybee.cloud.framework.base.exception.business.BaseBizException;
import com.honeybee.cloud.framework.base.exception.business.BaseBizExceptionEnum;
import com.ice.work.moment.crawler.service.IHandlerService;
import com.ice.work.moment.facade.crawler.enums.HandlerTypeEnum;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.context.annotation.Bean;

import java.util.Map;
import java.util.Objects;

/**
 * @Description HandlerContext
 * @Author DELL
 * @Create 2019-08-29
 * @Since 1.0.0
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class HandlerContext {

    private Map<Integer, Class> handlerMap;

    @Bean
    public IHandlerService getInstance(Integer type) {
        if(!HandlerTypeEnum.isEnum(type)){
            throw BaseBizException.getInstance(BaseBizExceptionEnum.STRATEGY_EXP);
        }
        Class clazz = handlerMap.get(type);
        if (Objects.isNull(clazz)) {
            throw BaseBizException.getInstance(BaseBizExceptionEnum.STRATEGY_EXP);
        }
        String className = StrUtil.lowerFirst(clazz.getSimpleName());
        return SpringContextHolder.containsBean(className) ? SpringContextHolder.getBean(className) : ReflectUtil.newInstance(clazz.getName());
    }
}
